package com.alibaba.dubbo.remoting.msgcodec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.interfaces.RSAPrivateKey;

import com.alibaba.dubbo.common.configure.ExtensionConfiguratorUtils;
import com.alibaba.dubbo.remoting.MessageDecode;

public class RSADecode extends RSACodec implements MessageDecode {
	private RSAPrivateKey privateKey;

	public RSAPrivateKey getPrivateKey() {
		return privateKey;
	}

	public void setPrivateKey(RSAPrivateKey privateKey) {
		this.privateKey = privateKey;
	}
	
	public RSADecode(){
		ExtensionConfiguratorUtils instance = ExtensionConfiguratorUtils.getInstance();
		String name = ExtensionConfiguratorUtils.combine(RSADecode.class, "privateKey");
		Object value = instance.getValue(name);
		if(value == null){
			try {
				privateKey = (RSAPrivateKey) getPrivateKeyWithBase64(
						"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAI86QeL7/UU+T5RpXg15RDhOTU0L"+ 
						"B/IFBdFvwy17G2Um++4jAL8ewIU7BIFsd6IKu8sYA0/yLeQoQ9ZyiBOhWvQqvp147s2GubanPQFb"+
						"7eynPTckkSwv1awboxFyXgWYKEiwsdl8GpglMnFLtnF9iAc3nOfuMfci5Hockf4Ej/vpAgMBAAEC"+
						"gYBcwlIheymQSsanS4ZKG5t/C9csalR+/ZnDBirVrcEURacrlyfIn1X38zz7xQ/FtkXhRm/+us3V"+
						"0e39WLegXwPT3kNyE17FB8pOQDFjLVNK8TFI2soHk5hK5XzkcrNlI7hyh6uLn71MxdLMdjDo+pZV"+
						"2QpoDOLqPuKu69uDMax4AQJBAMBP9pokdHWZomWX180JZCl/pojw4tWJUyv9+nODskyav+ce9I2B"+
						"fHwfeYk7s+Jy96c68IeAJqjXjAUgeem3SakCQQC+qPAfqO5d37Lq3dBS/0+yI/26nEqfIVcLJlIV"+
						"EuChSWnPHDkiwLIRDzC9NjQ2N0r3OtoLT9gjT/Df9pmqkQhBAkAmNv2a7cmSoN/rbjv8y3Py5yHR"+
						"roR0yGAVqtd84tuoa0vdAoK4J9Xz2FFPWuTJB+18drLbSjTkckipsCVpsvlZAkEAlMADUAAhsPXF"+
						"hn52eTqeOBLic4Rap9qAKb/FDJIE1XEMbzzKyvViN/MNCKJQi/gJseellGu/6pUFDgc8jpnGwQJB"+
						"AI2iVqiVx+KJXA+ZNmxOChc0GAsRgx7fURt+13RCDixHBCVKaGHldo+coKSR/J36jWuhKFVUgf4a"+
						"EcYqO1jiBMY=");
			} catch (Exception e) {
				throw new IllegalArgumentException(e);
			}
		}else if(value instanceof byte[]){
			try {
				privateKey = (RSAPrivateKey)getPrivateKey((byte[])value);
			} catch (Exception e) {
				throw new IllegalArgumentException(e);
			}
		}else {
			try {
				privateKey = (RSAPrivateKey) getPrivateKeyWithBase64(value.toString());
			} catch (Exception e) {
				throw new IllegalArgumentException(e);
			}
		}
	}

	@Override
	public int decode(InputStream in, OutputStream out/*,
			MessageEncodeRegistry registry*/) throws IOException {
		try {
			int ret = decrypt(in, out, privateKey);
			//registry.appendEncode("rsa");
			return ret;
		} catch (Exception e) {
			throw new IOException(e);
		}
	}
}
